package in.muton.edushare.poll.questions;

import in.muton.edushare.pages.EduShareBasePage;

import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.PollQuestions;

public class FreeformQuestion extends QuestionBase {

	public FreeformQuestion(String id, IModel<PollQuestions> model,
			EduShareBasePage page, final boolean preview, final boolean editMode) {
		super(id, model, page, preview, editMode);
		retrieveValues();
		add(new TextArea<String>("answer", new PropertyModel<String>(this,
				"answer")));
	}

	private String answer = "";
	private static final long serialVersionUID = -4382864048270784867L;

	public void setAnswer(String answer) {
		this.answer = answer;
	}

	public String getAnswer() {
		return answer;
	}

	@Override
	public boolean retrieveValues() {
		UserPollDAO upDAO = new UserPollDAO(getORMInterface());
		setAnswer(upDAO.getStringAnswer(getLoggedInUser(), getQuestionModel()
				.getObject()));
		return false;
	}

	@Override
	public boolean save(boolean draft) {
		if ((!draft && !verify()) || isEditMode() ||isPreview())
			return false;
		UserPollDAO upDAO = new UserPollDAO(getORMInterface());
		upDAO.setAnswer(getLoggedInUser(), getQuestionModel().getObject(),
				getAnswer());
		return true;
	}

	@Override
	public boolean verify() {
		if (!StringUtil.isValid(getAnswer()) && getQuestionModel().getObject().isRequired()){
			setError("Please respond to question no. "
					+ getQuestionModel().getObject().getQuestionSerialNo());
			return false;
		}
		if(StringUtil.isValid(getAnswer()) && 
				getAnswer().length() >= ApplicationConstants.LONG_QUESTION_LENGTH){
			setError("Your response to question no. "+ getQuestionModel().getObject().getQuestionSerialNo()+" is too long. Limit is 4000 characters.");
			return false;
		}
		return true;
	}

	@Override
	public void clear() {
		new UserPollDAO(getORMInterface()).clearAnswers(getLoggedInUser(),
				getQuestionModel().getObject());
		setAnswer("");
	}
}
